package com.util.KeyInfo;

import com.util.PublicUtil;

import javax.sql.DataSource;
import java.sql.PreparedStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: Ryan lee
 * Date: Mar 15, 2008
 * Time: 7:06:50 PM
 * To change this template use File | Settings | File Templates.
 */


    public class KeyInfo {

    private long keyMax = 1;

    private long keyMin;

    private long nextKey;

    private int poolSize;

    private String KeyName;

    public DataSource getDateSource() {
        return dateSource;
    }

    public void setDateSource(DataSource dateSource) {
        this.dateSource = dateSource;
    }

    private DataSource dateSource ;




    /**
     * @param poolSize
     * @param KeyName  the name of the key
     */
    public KeyInfo(int poolSize, String KeyName)  {
        this.poolSize = poolSize;
        this.KeyName = KeyName;
        retrieveFromDB();
    }

    public KeyInfo(int poolSize, String KeyName, DataSource ds)  {
        this.dateSource = ds;
        this.poolSize = poolSize;
        this.KeyName = KeyName;
        retrieveFromDB();
    }

    /**
     * @return keyMax
     */
    public long getKeyMax() {
        return keyMax;
    }

    /**
     * @return KeyMin
     */
    public long getKeyMin() {
        return keyMin;
    }

    /**
     *
     */
    public long getNextKey()  {
        if (nextKey > keyMax) {
            retrieveFromDB();
        }
        return nextKey++;
    }

    /**
     *
     */
    public void retrieveFromDB()  {
        Logger log = Logger.getLogger(this.getClass());
        String sqlstr = "select KeyCurrentValue from t_keyinfo where KeyName=? ";
        Connection conn = null;
        //Statement stmt1;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = dateSource.getConnection();
            pstmt = conn.prepareStatement(sqlstr);
            pstmt.setString(1, KeyName);
            rs = pstmt.executeQuery();

            long currval = 0;
            boolean hasThisKeyName = false;
            if (rs.next()) {
                currval = rs.getLong("KeyCurrentValue");
                hasThisKeyName = true;
            }
            //
            keyMax = currval + poolSize;
            //
            keyMin = currval + 1;
            nextKey = keyMin;
            //
            if (hasThisKeyName) {
                //sqlstr = new StringBuilder().append(" update t_keyinfo set KeyCurrentValue=").append(keyMax).append(" where KeyName ='").append(KeyName).append("'").toString();
                sqlstr = " update t_keyinfo set KeyCurrentValue=? where KeyName =? ";

            } else {
                //sqlstr = new StringBuilder().append("INSERT INTO t_keyinfo  (KeyCurrentValue,KeyName)VALUES   (").append(keyMax).append(",'").append(KeyName).append("')").toString();
                sqlstr = "INSERT INTO t_keyinfo  (KeyCurrentValue,KeyName)VALUES   (?,?)";
            }
            // stmt1.executeUpdate(sqlstr);
            pstmt = conn.prepareStatement(sqlstr);
            pstmt.setLong(1, keyMax);
            pstmt.setString(2, KeyName);
            pstmt.executeUpdate();
        } catch (SQLException e) {

            log.error("Error retrieveFromDB()",e);

        } finally {
            //
            try {
                if (rs != null) {
                    rs.close();

                }
            }
            catch (Exception ex) {

                log.error(ex);
            }

            try {
                if (pstmt != null) {
                    pstmt.close();

                }
            }
            catch (Exception ex) {

                log.error(ex);

            }
            try {
                if (conn != null) {
                    conn.close();
                }
            }
            catch (Exception ex) {
                
                log.error(ex);
            }


        }
    }
}
